package com.xunji.xunji.ui;

import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;

import com.huanxiao.base.base.BaseFragment;
import com.huanxiao.base.common.bean.EventMessage;
import com.huanxiao.base.constant.Const;
import com.xunji.xunji.R;


/**
 * Created by paul on 16/10/19.
 */

public class WebViewFragment extends BaseFragment {

    private static final String EXTRA_TITLE = "title";
    private static final String EXTRA_URL = "url";
    private static final String EXTRA_SHOW_NAVI = "is_show_navi";


    private String mUrlString;
    private String mTitle;
    private WebView mWebView;

    private boolean isShowNavi = false;

    private SwipeRefreshLayout mSwipeRefreshLayout;

    public static WebViewFragment newInstance(String title, String url) {

        Bundle args = new Bundle();

        WebViewFragment fragment = new WebViewFragment();
        args.putString(EXTRA_TITLE, title);
        args.putString(EXTRA_URL, url);
        fragment.setArguments(args);
        return fragment;
    }


    public static WebViewFragment newInstance(String title, String url, boolean showNavi) {

        Bundle args = new Bundle();

        WebViewFragment fragment = new WebViewFragment();
        args.putString(EXTRA_TITLE, title);
        args.putString(EXTRA_URL, url);
        args.putBoolean(EXTRA_SHOW_NAVI, showNavi);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutID() {
        return R.layout.fragment_webview;
    }

    @Override
    public void initView(View view) {
        mWebView = (WebView) view.findViewById(R.id.webview);
        mSwipeRefreshLayout = fvById(view, R.id.swipe_refresh);
        if (mWebView != null && ((mUrlString != null && mUrlString.length() > 0))) {
            try {

                WebSettings webSettings = mWebView.getSettings();
                webSettings.setSaveFormData(false);
                webSettings.setJavaScriptEnabled(true);
                webSettings.setDefaultTextEncodingName("utf-8");
                webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
                webSettings.setSupportZoom(false);
                /***打开本地缓存提供JS调用**/
                mWebView.getSettings().setDomStorageEnabled(true);
                mWebView.getSettings().setDatabaseEnabled(false);
                // This next one is crazy. It's the DEFAULT location for your app's cache
                // But it didn't work for me without this line.
                // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
                String appCachePath = getActivity().getApplicationContext().getCacheDir().getAbsolutePath();
                mWebView.getSettings().setAppCachePath(appCachePath);
                mWebView.getSettings().setAllowFileAccess(true);
                mWebView.getSettings().setAppCacheEnabled(false);
                mWebView.setWebChromeClient(new WBChromeClient());

                // 修改User-Agent使得web端正确判断
                mWebView.clearHistory();
                mWebView.clearCache(true);
                mWebView.clearSslPreferences();
                mWebView.requestFocus();


                Log.e("HPG", mUrlString);
//                mUrlString = getUrlString(mUrlString);
                mWebView.loadUrl(mUrlString);


//                setNavigationText(mTitle);


                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
                }
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
//                }
//                if (Const.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                    mWebView.setWebContentsDebuggingEnabled(true);
//                }

            } catch (Throwable e) {
                e.printStackTrace();
            }


        }
        showNaviBackIcon(isShowNavi);
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initBundleExtras(Bundle extras) {
        mTitle = extras.getString(EXTRA_TITLE);

        if (extras.containsKey(EXTRA_URL)) {
            mUrlString = extras.getString(EXTRA_URL);
            mUrlString = getUrlString(mUrlString);
        }

        if (extras.containsKey(EXTRA_SHOW_NAVI)) {
            isShowNavi = extras.getBoolean(EXTRA_SHOW_NAVI);

        }
    }


    /**
     * 根据不同情况获取具体的URL
     *
     * @param url
     * @return
     */
    private String getUrlString(String url) {
        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            if (!builder.toString().contains("be-app")) {
                builder.append("&be-app=1");
            }
            if (!TextUtils.isEmpty(Const.TOKEN)) {
                builder.append("&token=" + Const.TOKEN);
            }
        } else {
            if (!builder.toString().contains("be-app")) {
                builder.append("?be-app=1");
            }

            if (!TextUtils.isEmpty(Const.TOKEN)) {
                builder.append("&token=" + Const.TOKEN);

            }
        }

        int i = builder.toString().lastIndexOf("/");
        if ("?".equals(builder.toString().indexOf(i + 1))) {
            builder.replace(i, i + 1, "");
        }
        return builder.toString();
    }

    @Override
    public void initListener() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mWebView.reload();
            }
        });

    }

    @Override
    public void onDestroyView() {
        if (mWebView != null) {
            mWebView.destroyDrawingCache();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroyView();
    }

    @Override
    public boolean isBindEventBus() {
        return true;
    }


    @Override
    public void onEventBusListener(EventMessage message) {
        super.onEventBusListener(message);


    }

    public class WBChromeClient extends WebChromeClient {


        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//            result.confirm();
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {

            super.onReceivedTitle(view, title);
//            if (TextUtils.isEmpty(mTitle)) mToolbar.setTitleText(title);
            mSwipeRefreshLayout.setRefreshing(false);
        }

    }


}
